<template>
  <div class="app-container">
    <div class="filter-container" style="margin-bottom: 10px">
      <el-input
        v-model="searchObj.hosname"
        class="filter-item"
        style="width: 200px; margin-right: 10px"
        placeholder="医院名称"
        @keyup.enter.native="handleFilter"
      />
      <el-select v-model="searchObj.status" placeholder="状态">
        <el-option
          v-for="item in statusOptions"
          :key="item.key"
          :label="item.display_name"
          :value="item.key"
        />
      </el-select>
      <el-button
        class="filter-item"
        type="primary"
        style="margin-left: 15px"
        icon="el-icon-search"
        @click="handleFilter"
      >查询</el-button>
      <el-button
        class="filter-item"
        style="margin-left: 15px"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >添加</el-button>
      <el-button
        class="filter-item"
        style="margin-left: 15px"
        type="primary"
        icon="el-icon-delete"
        @click="handleBatchDel"
      >删除</el-button>
      <el-button
        class="filter-item"
        style="margin-left: 15px"
        type="primary"
        icon="el-icon-document"
        @click="handleExport"
      >导出</el-button>
    </div>
    <el-table
      ref="multipleTable"
      :data="tableData"
      border
      stripe
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" align="center" />
      <el-table-column
        label="序号"
        sortable="custom"
        :class-name="getSortClass('id')"
      >
        <template slot-scope="{ row }">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="hosname" label="医院名称" />
      <el-table-column prop="hoscode" label="医院编码" />
      <el-table-column prop="status" label="医院状态">
        <template slot-scope="{ row }">
          <el-tag :type="row.status | statusFilter">
            {{ row.status | statusFormat }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作">
        <template slot-scope="scope">
          <el-button
            type="success"
            size="small"
            @click="handleLook(scope.row)"
          >查看</el-button>
          <el-button
            type="primary"
            size="small"
            @click="handleUpdate(scope.row)"
          >编辑</el-button>
          <el-button
            v-if="scope.row.status == 1"
            type="warning"
            size="small"
            @click="handleLock(scope.row, 0)"
          >禁用</el-button>
          <el-button
            v-if="scope.row.status != 1"
            type="warning"
            size="small"
            @click="handleLock(scope.row, 1)"
          >启用</el-button>
          <el-button
            type="danger"
            size="small"
            @click="handleDel(scope.row, scope.$index)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :current-page="searchObj.current"
      :page-sizes="[1, 2, 3, 4]"
      :page-size="searchObj.limit"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="formData"
        :rules="rules"
        :model="formData"
        style="width: 400px"
      >
        <el-form-item label="医院名称" prop="hosname">
          <el-input v-model="formData.hosname" />
        </el-form-item>
        <el-form-item label="医院编码" prop="hoscode">
          <el-input v-model.number="formData.hoscode" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="formData.status" placeholder="状态">
            <el-option
              v-for="item in statusOptions"
              :key="item.key"
              :label="item.display_name"
              :value="item.key"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="dialogStatus === 'create' ? createData() : updateData()"
          >提交</el-button>
          <el-button @click="restForm('formData')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog title="查看" :visible.sync="dialogTableVisible">
      <el-form :model="dialogData" style="width: 400px">
        <el-form-item label="医院名称" prop="hosname">
          {{ dialogData.hosname }}
        </el-form-item>
        <el-form-item label="医院编码" prop="hoscode">
          {{ dialogData.hoscode }}
        </el-form-item>
        <el-form-item label="状态" prop="status">
          {{ dialogData.status | statusFormat }}
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="dialogTableVisible = false"
        >关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  getHospSetList,
  editHospSet,
  addHospSet,
  delHospSet,
  batchDelHospSet,
  lockOrUnlockHospSet
} from '@/api/hospset'

const statusOptions = [
  { key: 1, display_name: '已启用' },
  { key: 0, display_name: '已禁用' }
]

export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        1: 'success',
        0: 'danger'
      }
      return statusMap[status]
    },
    statusFormat(status) {
      const statusMap = {
        1: '已启用',
        0: '已禁用'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      total: 0,
      searchObj: {
        current: 1,
        limit: 4,
        hosname: undefined,
        hoscode: undefined,
        status: undefined
      },
      statusOptions,
      list: [],
      tableData: [],
      dialogData: {},
      multipleSelection: [],
      multipleIDs: [],
      formData: {
        id: undefined,
        hosname: '',
        hoscode: ''
      },
      dialogFormVisible: false,
      dialogTableVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      rules: {
        hosname: [
          { required: true, message: '请输入医院名称', trigger: 'blur' }
        ],
        hoscode: [
          { required: true, message: '请输入医院编码', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择医院状态', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    handleFilter() {
      this.searchObj.current = 1
      this.fetchData()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
      this.multipleIDs = []
      this.multipleSelection.map((item) => {
        this.multipleIDs.push(item.id)
      })
      // this.multipleSelection = val
    },
    handleCreate() {
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.restFormData()
        this.$refs.formData.clearValidate()
      })
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.searchObj.current = 1
      this.searchObj.limit = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.searchObj.current = val
      this.fetchData()
    },
    handleLook(row) {
      this.dialogTableVisible = true
      this.$nextTick(() => {
        this.dialogData = Object.assign({}, row)
      })
    },
    handleLock(row, status) {
      row.status = status
      lockOrUnlockHospSet(row.id, status).then((response) => {
        if (response.code === 200) {
          this.$message({
            type: 'success',
            message: status === 1 ? '启用成功!' : '禁用成功!'
          })
        } else {
          this.$message({
            type: 'error',
            message: status === 1 ? '启用失败!' : '禁用失败!'
          })
        }
      })
    },
    handleUpdate(row) {
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.formData = Object.assign({}, row)
        this.$refs.formData.clearValidate()
      })
    },
    handleDel(row, index) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        distinguishCancelAndClose: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: 'true'
      })
        .then(() => {
          delHospSet(row.id).then((response) => {
            if (response.code === 200) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
              // this.tableData.splice(index, 1)
              this.fetchData()
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    handleBatchDel() {
      if (this.multipleSelection.length) {
        batchDelHospSet(this.multipleIDs).then((response) => {
          if (response.code === 200) {
            this.$message({
              message: 'Batch Remove Success',
              type: 'success'
            })
            this.$refs.multipleTable.clearSelection()
            this.fetchData()
          }
        })
      } else {
        this.$message({
          message: 'Please select at least one item',
          type: 'warning'
        })
      }
    },
    createData() {
      this.$refs.formData.validate((valid) => {
        if (valid) {
          addHospSet(this.formData).then((response) => {
            if (response.code === 200) {
              // this.tableData.unshift(this.formData)
              this.dialogFormVisible = false
              this.$notify({
                title: 'Success',
                message: 'Add Successfully',
                type: 'success',
                duration: 2000
              })
              // this.$router.push({ path: '/hospSet' })
              this.fetchData()
            }
          })
        }
      })
    },
    updateData() {
      this.$refs.formData.validate((valid) => {
        if (valid) {
          editHospSet(this.formData).then((response) => {
            if (response.code === 200) {
              this.dialogFormVisible = false
              const index = this.tableData.findIndex(
                (v) => v.id === this.formData.id
              )
              this.tableData.splice(index, 1, this.formData)
              this.$notify({
                title: 'Success',
                message: 'Update Successfully',
                type: 'success',
                duration: 2000
              })
            } else {
              this.$notify({
                title: 'Error',
                message: 'Update Error',
                type: 'error',
                duration: 2000
              })
            }
          })
        }
      })
    },
    restFormData() {
      this.formData = {
        id: undefined,
        hosname: '',
        hoscode: '',
        status: ''
      }
    },
    restForm(formName) {
      // this.$refs[formName].resetFields()
      this.$refs.formData.resetFields()
    },
    fetchData() {
      getHospSetList(
        this.searchObj.current,
        this.searchObj.limit,
        this.searchObj
      )
        .then((response) => {
          this.tableData = response.data.records
          this.total = response.data.total
        })
        .catch((error) => {
          console.log(error)
        })
    },
    handleExport() {
      if (this.multipleSelection.length) {
        import('@/vendor/Export2Excel').then((excel) => {
          const tHeader = ['序号', '医院名称', '医院编号', '状态']
          const filterVal = ['id', 'hosname', 'hoscode', 'status']
          const list = this.multipleSelection
          const data = this.formatJson(filterVal, list)
          excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: this.filename
          })
          this.$refs.multipleTable.clearSelection()
        })
      } else {
        this.$message({
          message: 'Please select at least one item',
          type: 'warning'
        })
      }
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) => filterVal.map((j) => v[j]))
    },
    getSortClass(id) {}
  }
}
</script>
